import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Row, Col, Menu, Popconfirm } from 'antd';
import { ContentPackage, PrimaryC, TreeChartsHC, SecondHeaderC } from '../../../comps';
import myStyle from './index.less';
import UpdataC from './UpdataC';
import DeleteC from './DeleteC';
@connect(({ institutionConfigurationM, loading }) => ({
  institutionConfigurationM,
  loading: loading.effects['institutionConfigurationM/queryInstitution'],
}))
export default class institutionConfigurationC extends PureComponent {
  state = {
    columns: [],
    dataSource: [], //处理后信息数据
    echartsDataSource: [], //echarts信息数据
    listDataSource: [], //租户列表信息
    searchObj: {}, //树形图查询条件
    listObj: {}, //列表查询条件
    editObj: {}, //编辑信息
    deleteId: {},
    visible: false, //模态框显示隐藏
    isEdit: false, //默认为新增（修改：true,新增：false
    disable: true, //按钮状态
    disable1: false,
    deleteVisible: false, //删除模态框显示隐藏
    superMan: false,
    nums: 1,
  };

  componentDidMount() {
    this.getUser();
    this.getTenantList();
    const tempObj = {};
  }

  //获取租户列表
  getTenantList = () => {
    const { dispatch } = this.props;
    const { listObj } = this.state;

    dispatch({
      type: 'institutionConfigurationM/getTenantList',
      payload: {
        ...listObj,
      },
      callback: (status, data) => {
        if (status == 'success' && data) {
          this.setState({
            listDataSource: data.dataSource,
          });
        }
      },
    });
  };

  //判断用户权限
  getUser = () => {
    this.props.dispatch({
      type: 'institutionConfigurationM/getUser',
      payload: localStorage.getItem('antd-pro-superManId'),
      callback: (data) => {
        if (data.data.superMan) {
          this.setState({
            superMan: data.data.superMan,
          });
        } else {
          const cod = {};
          cod.tenantId = data.data.tenant;

          this.setState(
            {
              searchObj: cod,
            },
            () => this.getTableData(),
          );
        }
      },
    });
  };

  //获取数据
  getTableData = () => {
    const { dispatch } = this.props;
    const { searchObj } = this.state;
    dispatch({
      type: 'institutionConfigurationM/queryInstitution',
      payload: {
        ...searchObj,
      },
      callback: (status, data) => {
        if (status == 'success' && data) {
          const data1 = [];
          data1.push(data.dataSource);
          const newData = this.toMapTree(data1);
          const nums = this.getTreeNodeNum(data1);
          this.setState({
            dataSource: data1,
            echartsDataSource: newData,
            nums: nums,
          });
        } else {
          this.setState({
            echartsDataSource: [],
          });
        }
      },
    });
  };

  isArray = (arr) => Array.isArray(arr);
  // 获取同一层节点数量
  getTreeNodeNum = (treeNodes) => {
    let queue = [],
      newQueue = [],
      result = [];
    if (this.isArray(treeNodes)) {
      result.push(treeNodes.length);
      queue.push(...treeNodes);
    } else {
      return [0];
    }
    do {
      let sum = 0;
      queue.forEach((item) => (this.isArray(item.children) ? (sum += item.children.length) : ''));
      result.push(sum);
      while (queue.length != 0) {
        let treeNode = queue.shift();
        if (this.isArray(treeNode.children)) {
          treeNode.children.forEach((item) => newQueue.push(item));
        }
      }
      [queue, newQueue] = [newQueue, queue];
    } while (queue.length != 0);

    return Math.ceil(Math.max.apply(null, result) / 10);
  };
  //提取数据函数
  toMapTree = (dataSource) =>
    dataSource.map((item) => {
      const { instName, id, children = [] } = item;
      return {
        name: instName,
        value: id,
        children: Array.isArray(children) && children.length ? this.toMapTree(children) : [],
      };
    });

  findCode = (id, Data) => {
    let target = '';
    Data.forEach((item) => {
      if (item.id == id) {
        target = item.code;
      }
    });
    return target;
  };

  //根据ID提取项模态框传递的数据
  findTargetById = (id, treeData) => {
    let target = {};
    const findItem = (data) => {
      data.forEach((item) => {
        if (item.id === id) {
          target = item;
          return;
        } else if (Array.isArray(item.children) && item.children.length) {
          findItem(item.children);
        }
      });
    };
    findItem(treeData);
    return target;
  };

  // 新增模态框打开
  addModalOpen = () => {
    this.setState({
      visible: true,
      isEdit: false,
    });
  };

  //修改模态框打开
  editAccount = () => {
    this.setState({
      visible: true,
      isEdit: true,
    });
  };

  // 改变visible
  changeVisible = (msg) => {
    this.setState({
      visible: msg,
      deleteVisible: msg,
    });
  };

  //子组件调用父组件的getTableData方法
  useGetTableData = () => {
    this.setState(
      {
        disable: true,
        disable1: false,
      },
      this.getTableData(),
    );
  };

  //根据点击返回列表id
  handleClick = (e) => {
    const cod = {};
    cod.tenantId = this.findCode(e.key, this.state.listDataSource);
    this.setState(
      {
        searchObj: cod,
        disable: true,
        disable1: false,
        nums: [],
      },
      () => this.getTableData(),
    );
  };

  //echarts点击函数
  echartsOnChange = (e) => {
    const editData = this.findTargetById(e.value, this.state.dataSource);
    if (e.value == 'root') {
      this.setState({
        disable: false,
        disable1: true,
        editObj: editData,
        deleteId: editData,
      });
    } else {
      this.setState({
        disable: false,
        disable1: false,
        editObj: editData,
        deleteId: editData,
      });
    }
  };
  // 删除按钮点击
  deleteConfirm = () => {
    const value = {
      id: this.state.deleteId.id,
    };
    this.props.dispatch({
      type: 'institutionConfigurationM/deleteInstitutionById',
      payload: value,
      callback: (res) => {
        this.useGetTableData();
      },
    });
  };

  render() {
    return (
      <ContentPackage
        title='机构配置'
        contentHtml={
          <div className={myStyle.back}>
            {this.state.superMan ? (
              <Row>
                <Col span={4}>
                  <div>
                    <SecondHeaderC title='租户列表' />
                  </div>
                  <div style={{ height: 'calc(100vh - 165px)', overflow: 'scroll' }}>
                    <Menu onClick={this.handleClick} style={{ border: 'none' }}>
                      {this.state.listDataSource.map((item) => (
                        <Menu.Item key={item.id}>{item.name}</Menu.Item>
                      ))}
                    </Menu>
                  </div>
                </Col>
                <Col span={20}>
                  <div>
                    <PrimaryC title='添加' style={{ marginLeft: '10px' }} onClick={this.addModalOpen} disabled={this.state.disable} />
                    <PrimaryC title='编辑' style={{ marginLeft: '10px' }} onClick={this.editAccount} disabled={this.state.disable1 ? this.state.disable1 : this.state.disable} />
                    <Popconfirm title={'确定删除？'} icon={<QuestionCircleOutlined />} onConfirm={this.deleteConfirm}>
                      <PrimaryC title='删除' style={{ marginLeft: '10px' }} disabled={this.state.disable1 ? this.state.disable1 : this.state.disable} />
                    </Popconfirm>

                    {this.state.visible ? (
                      <UpdataC
                        useGetTableData={this.useGetTableData}
                        editObj={this.state.editObj}
                        visible={this.state.visible}
                        changeVisible={this.changeVisible}
                        isEdit={this.state.isEdit}
                      />
                    ) : null}
                    {this.state.deleteVisible ? (
                      <DeleteC useGetTableData={this.useGetTableData} deleteId={this.state.deleteId} visible={this.state.deleteVisible} changeVisible={this.changeVisible} />
                    ) : null}
                  </div>
                  <div>
                    <TreeChartsHC data={this.state.echartsDataSource} height={this.state.nums * 800} selectedOnChange={(e) => this.echartsOnChange(e)} />
                  </div>
                </Col>
              </Row>
            ) : (
              <Row>
                <Col span={24}>
                  <div>
                    <PrimaryC title='添加' style={{ marginLeft: '10px' }} onClick={this.addModalOpen} disabled={this.state.disable} />
                    <PrimaryC title='编辑' style={{ marginLeft: '10px' }} onClick={this.editAccount} disabled={this.state.disable1 ? this.state.disable1 : this.state.disable} />
                    <Popconfirm title={'确定删除？'} icon={<QuestionCircleOutlined />} onConfirm={this.deleteConfirm}>
                      <PrimaryC title='删除' style={{ marginLeft: '10px' }} disabled={this.state.disable1 ? this.state.disable1 : this.state.disable} />
                    </Popconfirm>
                    {this.state.visible ? (
                      <UpdataC
                        useGetTableData={this.useGetTableData}
                        editObj={this.state.editObj}
                        visible={this.state.visible}
                        changeVisible={this.changeVisible}
                        isEdit={this.state.isEdit}
                        dataSource={this.state.dataSource}
                      />
                    ) : null}
                    {this.state.deleteVisible ? (
                      <DeleteC useGetTableData={this.useGetTableData} deleteId={this.state.deleteId} visible={this.state.deleteVisible} changeVisible={this.changeVisible} />
                    ) : null}
                  </div>
                  <div>
                    <TreeChartsHC data={this.state.echartsDataSource} height={this.state.nums * 800} selectedOnChange={(e) => this.echartsOnChange(e)} />
                  </div>
                </Col>
              </Row>
            )}
          </div>
        }
      />
    );
  }
}
